<template>
  <div class="app-container">


    <!-- 当前选中用户信息 -->
    <el-card class="selected-user-card" v-if="selectedUser.userId">
      <div slot="header" class="clearfix">
        <span>当前选中用户：{{ selectedUser.userName }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="clearSelectedUser">清除选择</el-button>
      </div>
      <el-descriptions :column="4" border>
        <el-descriptions-item label="用户名称">{{ selectedUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ selectedUser.deptName }}</el-descriptions-item>
        <el-descriptions-item label="岗位">{{ selectedUser.postName }}</el-descriptions-item>
        <el-descriptions-item label="最后考核时间" :span="2">
          <span v-if="selectedUser.lastAssessDate">{{ parseTime(selectedUser.lastAssessDate, '{y}-{m}-{d}') }}</span>
          <span v-else>暂无数据</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 最终分数查询区域 -->
    <el-card class="score-card" v-if="(isSuperAdmin() || isManager()) ? true : (selectedUser.userId || isEmployee())">
      <div slot="header" class="clearfix">
        <span>最终分数查询</span>
      </div>
      <el-button type="success" icon="el-icon-calendar" size="mini" @click="handleTodayFilter">今日筛选</el-button>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px" :rules="queryRules">
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="queryParams.startDate"
            type="date"
            placeholder="开始日期"
            value-format="yyyy-MM-dd"
            clearable
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="queryParams.endDate"
            type="date"
            placeholder="结束日期"
            value-format="yyyy-MM-dd"
            clearable
          />
        </el-form-item>
        <el-form-item label="除数" prop="divisor">
          <el-input
            v-model.number="queryParams.divisor"
            placeholder="用于计算平均分的除数（必填，默认24）"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询分数</el-button>

          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="isSuperAdmin() || isManager()">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:finalScore:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 分数列表：按角色分组展示 -->
    <div v-loading="loading">
      <el-collapse v-model="activeScoreRoles" accordion>
        <el-collapse-item v-for="(group, idx) in groupedScores" :key="group.roleKey || idx" :name="group.roleKey || String(idx)">
          <template slot="title">
            <span>角色：{{ group.roleName || '我的数据' }}（{{ (group.rows || []).length }}人）</span>
          </template>
          <el-table :data="group.rows" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" v-if="isSuperAdmin() || isManager()" />
            <el-table-column label="用户ID" align="center" prop="userId" v-if="isSuperAdmin() || isManager()" />
            <el-table-column label="用户名称" align="center" prop="userName" />

            <el-table-column label="最终分数" align="center" prop="finalScore" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.finalScore !== null && scope.row.finalScore !== undefined" :type="getScoreTagType(scope.row.finalScore)" size="small">
                  {{ scope.row.finalScore }}
                </el-tag>
                <span v-else>暂无数据</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleView(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 详情对话框：每天数据 -->
    <el-dialog title="每日分数明细" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名称">{{ detailForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="查询区间" :span="1">
          {{ queryParams.startDate }} ~ {{ queryParams.endDate }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">每日分数</el-divider>
      <el-table :data="scoreDetails" border>
        <el-table-column label="日期" prop="date" />
        <el-table-column label="分数" prop="score" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listFinalScore, getFinalScore, getScoreWithUsers, getMonthDailyScores } from "@/api/system/finalScore";
import { getAssessRolesWithUsers } from "@/api/system/assessUser";
import { listUser } from "@/api/system/user";
import { mapGetters } from 'vuex';

export default {
  name: "FinalScore",
  computed: {
    ...mapGetters(['roles', 'permissions', 'id'])
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 最终分数表格数据
      finalScoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      detailOpen: false,
      // 详情表单参数
      detailForm: {},
      // 分数明细
      scoreDetails: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        startDate: null,
        endDate: null,
        divisor: 24
      },
      // 表单校验规则
      queryRules: {
        divisor: [
          { required: true, message: '请输入除数', trigger: 'blur' },
          { type: 'number', message: '除数必须为数字', trigger: 'blur' }
        ]
      },
      // 用户相关数据
      userList: [],
      userTotal: 0,
      userLoading: false,
      selectedUser: {},
      // 按角色分组的可管理员工
      rolesWithUsers: [],
      activeRoles: [],
      // 分数列表按角色分组
      activeScoreRoles: [],
      // 日历/详情
      calendarOpen: false,
      selectedDate: new Date(),
      selectedDateForDetail: '',
      monthlyScores: {},
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        deptName: null
      }
    };
  },
  created() {
    this.initQueryParams();
    // 若未选择日期，默认使用本月的起止日期
    if (!this.queryParams.startDate || !this.queryParams.endDate) {
      const { start, end } = this.getThisMonthRange();
      this.queryParams.startDate = start;
      this.queryParams.endDate = end;
    }
    if (this.isSuperAdmin() || this.isManager()) {
      this.getRolesWithUsers();
    } else {
      this.getList();
    }
  },
  methods: {
    /** 初始化查询参数 */
    initQueryParams() {
      // 根据用户角色设置查询参数
      if (this.isSuperAdmin()) {
        // 超级管理员：展示所有数据，不限制查询条件
        this.showSearch = true;
      } else if (this.isManager()) {
        // 主管：展示手下员工的数据
        this.showSearch = true;
        // 根据主管角色设置部门过滤条件
        this.setManagerDeptFilter();
      } else {
        // 普通员工：只展示自己的数据，但允许使用筛选区间与除数
        this.queryParams.userId = this.id;
        this.showSearch = true;
      }
    },

    /** 设置主管部门过滤条件 */
    setManagerDeptFilter() {
      // 根据主管角色设置对应的部门过滤条件
      if (this.roles.includes('售前主管')) {
        this.userQueryParams.deptName = '售前';
      } else if (this.roles.includes('售中主管')) {
        this.userQueryParams.deptName = '售中';
      } else if (this.roles.includes('售后主管')) {
        this.userQueryParams.deptName = '售后';
      }else if (this.roles.includes('技术主管')) {
        this.userQueryParams.deptName = '技术';
      }
    },

    /** 查询按角色分组的员工列表（管理员/主管） */
    getRolesWithUsers() {
      this.userLoading = true;
      getAssessRolesWithUsers({ userName: this.userQueryParams.userName, deptName: this.userQueryParams.deptName }).then(response => {
        this.rolesWithUsers = response.data || [];
        this.userLoading = false;
      }).catch(() => { this.userLoading = false; });
    },

    /** 用户搜索按钮操作 */
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      if (this.isSuperAdmin() || this.isManager()) {
        this.getRolesWithUsers();
      }
    },

    /** 用户重置按钮操作 */
    resetUserQuery() {
      this.resetForm("userQueryForm");
      this.userQueryParams.userName = null;
      this.userQueryParams.deptName = null;
      this.handleUserQuery();
    },

    /** 选择用户 */
    handleUserSelect(row) {
      this.selectedUser = row;
      this.queryParams.userId = row.userId;
      this.getList();
    },

    /** 查看用户分数日历 */
    handleViewCalendar(row) {
      this.selectedUser = row;
      this.queryParams.userId = row.userId;
      this.calendarOpen = true;
      this.fetchMonthlyScores(row.userId);
    },

    /** 获取某用户某月每天总分 */
    fetchMonthlyScores(userId) {
      const ym = this.formatYearMonth(this.selectedDate);
      getMonthDailyScores({ yearMonth: ym, userId }).then(res => {
        const list = res.data || res || [];
        const map = {};
        list.forEach(item => {
          const day = this.normalizeDate(item.taskDate);
          map[day] = Number(item.score || 0);
        });
        this.monthlyScores = map;
      }).catch(() => { this.monthlyScores = {}; });
    },

    /** 清除选中的用户 */
    clearSelectedUser() {
      this.selectedUser = {};
      this.queryParams.userId = null;
      this.finalScoreList = [];
      this.total = 0;
    },

    /** 判断是否为超级管理员 */
    isSuperAdmin() {
      return this.roles && this.roles.includes('admin');
    },

    /** 判断是否为主管 */
    isManager() {
      const managerRoles = ['售前主管', '售中主管', '售后主管','技术主管'];
      return this.roles && this.roles.some(role => managerRoles.includes(role));
    },

    /** 判断是否为普通员工 */
    isEmployee() {
      const employeeRoles = ['售前', '售中', '售后'];
      return this.roles && this.roles.some(role => employeeRoles.includes(role));
    },

    /** 查询最终分数列表 */
    async getList() {
      this.loading = true;

      // 组装查询参数
      const queryParams = { ...this.queryParams };

      if (this.isSuperAdmin() || this.isManager()) {
        // 管理员/主管：可不选用户，支持按姓名/部门筛选
        if (this.selectedUser && this.selectedUser.userId) {
          queryParams.userId = this.selectedUser.userId;
        } else {
          delete queryParams.userId;
        }
        if (this.userQueryParams) {
          if (this.userQueryParams.userName) queryParams.userName = this.userQueryParams.userName;
          if (this.userQueryParams.deptName) queryParams.deptName = this.userQueryParams.deptName;
        }
      } else {
        // 普通员工：仅查询自己的
        queryParams.userId = this.id;
      }

      try {
        const response = await getScoreWithUsers(queryParams);
        const list = response.data || response || [];
        this.finalScoreList = list;
        this.total = list.length;
        // 生成按角色分组的数据结构
        this.groupedScores = this.buildGroupedScores(list);
        // 若提供了开始/结束日期与除数，则按区间求和后除以除数，作为平均分
        if (this.queryParams.startDate && this.queryParams.endDate && Number(this.queryParams.divisor) > 0) {
          await this.computeAverageScoresForRange();
          // 重新生成分组（分数已更新）
          this.groupedScores = this.buildGroupedScores(this.finalScoreList);
        }
      } catch (e) {
        this.finalScoreList = [];
        this.total = 0;
        this.groupedScores = [];
      } finally {
        this.loading = false;
      }
    },
    buildGroupedScores(list) {
      // 依据角色信息分组。后端如返回 roleKey/roleName 则用之；
      // 若无角色信息，则将员工归为“我的数据”或“未分组”。
      const groupsMap = {};
      for (const row of list) {
        const roleKey = row.roleKey || 'self';
        const roleName = row.roleName || (this.isSuperAdmin() || this.isManager() ? '未分组' : '我的数据');
        if (!groupsMap[roleKey]) {
          groupsMap[roleKey] = { roleKey, roleName, rows: [] };
        }
        groupsMap[roleKey].rows.push(row);
      }
      return Object.values(groupsMap);
    },
    async computeAverageScoresForRange() {
      const start = new Date(this.queryParams.startDate);
      const end = new Date(this.queryParams.endDate);
      if (isNaN(start.getTime()) || isNaN(end.getTime()) || start > end) return;
      const months = this.enumerateYearMonths(start, end);
      const divisor = Number(this.queryParams.divisor);
      // 逐用户汇总区间内每天总分
      for (const row of this.finalScoreList) {
        const userId = row.userId;
        let totalScore = 0;
        for (const ym of months) {
          try {
            const res = await getMonthDailyScores({ yearMonth: ym, userId });
            const daily = res.data || res || [];
            for (const item of daily) {
              const day = this.normalizeDate(item.taskDate);
              const d = new Date(day);
              if (d >= start && d <= end) {
                totalScore += Number(item.score || 0);
              }
            }
          } catch (e) { /* ignore month errors */ }
        }
        const avg = totalScore / divisor;
        row.finalScore = Number.isFinite(avg) ? Number(avg.toFixed(2)) : null;
      }
    },
    /** 获取当前区间内的每日分数列表 */
    async fetchDailyScoresForRange(userId) {
      const start = new Date(this.queryParams.startDate);
      const end = new Date(this.queryParams.endDate);
      if (isNaN(start.getTime()) || isNaN(end.getTime()) || start > end) return [];
      const months = this.enumerateYearMonths(start, end);
      const resultMap = {};
      for (const ym of months) {
        try {
          const res = await getMonthDailyScores({ yearMonth: ym, userId });
          const daily = res.data || res || [];
          for (const item of daily) {
            const day = this.normalizeDate(item.taskDate);
            const d = new Date(day);
            if (d >= start && d <= end) {
              resultMap[day] = Number(item.score || 0);
            }
          }
        } catch (e) { /* ignore */ }
      }
      // 返回按日期升序的数组
      return Object.keys(resultMap).sort().map(date => ({ date, score: resultMap[date] }));
    },
    enumerateYearMonths(start, end) {
      const result = [];
      const sY = start.getFullYear();
      const sM = start.getMonth();
      const eY = end.getFullYear();
      const eM = end.getMonth();
      let y = sY, m = sM;
      while (y < eY || (y === eY && m <= eM)) {
        const mm = (m + 1).toString().padStart(2, '0');
        result.push(`${y}-${mm}`);
        m++;
        if (m > 11) { m = 0; y++; }
      }
      return result;
    },
    // 取消按钮
    cancel() {
      this.detailOpen = false;
      this.detailForm = {};
    },
    // 表单重置
    reset() {
      this.detailForm = {
        userId: null,
        userName: null,
        deptName: null,
        postName: null,
        assessMonth: null,
        finalScore: null,
        createTime: null
      };
      this.resetForm("detailForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 不选择日期默认使用本月
      if (!this.queryParams.startDate || !this.queryParams.endDate) {
        const { start, end } = this.getThisMonthRange();
        this.queryParams.startDate = this.queryParams.startDate || start;
        this.queryParams.endDate = this.queryParams.endDate || end;
      }
      // 基础数值校验
      if (this.queryParams.divisor == null || Number(this.queryParams.divisor) <= 0) {
        this.$message.error('除数为必填项且必须大于 0');
        return;
      }
      this.$refs.queryForm.validate((valid) => {
        if (!valid) return;
        this.queryParams.pageNum = 1;
        this.getList();
      });
    },
    /** 查看考核日历：选择某日后触发月分数刷新 */
    handleDateSelect(date) {
      this.selectedDateForDetail = this.normalizeDate(date);
      this.calendarOpen = false;
      // 展示详情弹窗也可以按需打开，这里只刷新月分数
      this.fetchMonthlyScores(this.selectedUser.userId || this.queryParams.userId);
    },
    formatYearMonth(d) {
      const y = d.getFullYear();
      const m = (d.getMonth() + 1).toString().padStart(2, '0');
      return `${y}-${m}`;
    },
    normalizeDate(val) {
      if (!val) return '';
      if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
      const d = new Date(val);
      const y = d.getFullYear();
      const m = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      return `${y}-${m}-${day}`;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 还原除数默认值
      this.queryParams.divisor = 24;
      // 还原为本月日期范围
      const { start, end } = this.getThisMonthRange();
      this.queryParams.startDate = start;
      this.queryParams.endDate = end;
      this.handleQuery();
    },
    /** 获取本月起止日期（yyyy-MM-dd） */
    getThisMonthRange() {
      const now = new Date();
      const first = new Date(now.getFullYear(), now.getMonth(), 1);
      const last = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      const toStr = (d) => {
        const y = d.getFullYear();
        const m = (d.getMonth() + 1).toString().padStart(2, '0');
        const day = d.getDate().toString().padStart(2, '0');
        return `${y}-${m}-${day}`;
      };
      return { start: toStr(first), end: toStr(last) };
    },
    /** 今日筛选按钮操作 */
    handleTodayFilter() {
      const today = new Date();
      const toStr = (d) => {
        const y = d.getFullYear();
        const m = (d.getMonth() + 1).toString().padStart(2, '0');
        const day = d.getDate().toString().padStart(2, '0');
        return `${y}-${m}-${day}`;
      };
      this.queryParams.startDate = toStr(today);
      this.queryParams.endDate = toStr(today);
      this.queryParams.divisor = 1;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 详情按钮操作 */
    handleView(row) {
      this.reset();
      const userId = row.userId;
      this.detailForm = { userName: row.userName };
      this.fetchDailyScoresForRange(userId).then((daily) => {
        this.scoreDetails = daily;
        this.detailOpen = true;
      }).catch(() => {
        this.scoreDetails = [];
        this.detailOpen = true;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/finalScore/export', {
        ...this.queryParams
      }, `最终分数_${new Date().getTime()}.xlsx`)
    },
    // 分数标签类型
    getScoreTagType(score) {
      const s = Number(score || 0);
      if (s >= 95) return 'success';
      if (s >= 85) return 'warning';
      return 'danger';
    },
    }
  }
;
</script>

<style scoped>
.user-card {
  margin-bottom: 20px;
}

.selected-user-card {
  margin-bottom: 20px;
  background-color: #f0f9ff;
}

.score-card {
  margin-bottom: 20px;
}

.user-card .el-table {
  cursor: pointer;
}

.user-card .el-table tbody tr:hover {
  background-color: #f5f7fa;
}
</style>
